package control;

import Util.PageUtil;
import bean.TArea;
import bean.TInsect;
import com.google.gson.Gson;
import serves.Impl.areaSevImpl;
import serves.areaSev;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "areaServlet",urlPatterns = "/area")
public class areaServlet extends HttpServlet {
    areaSev as = new areaSevImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String method = request.getParameter("method");
        if(method==null||method.equalsIgnoreCase("")) {
            areaShow(request, response);
        }else if(method.equalsIgnoreCase("Add")){
            areaAdd(request,response);
        }
    }

    private void areaAdd(HttpServletRequest request, HttpServletResponse response) {
        String areaName = request.getParameter("areaName");
        String treeType = request.getParameter("treeType");
        String landType = request.getParameter("landType");
        String advTree = request.getParameter("advTree");
        String mainClass = request.getParameter("mainClass");
        TArea ta = new TArea();
        ta.setFAreaName(areaName);
        ta.setFTreeType(treeType);
        ta.setFLand(landType);
        ta.setFAdvTree(advTree);
//        ta.setClassName(mainClass);
        boolean flag=as.add(ta);
        System.out.println("地区flag = " + flag);

    }

    private void areaShow(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();
        int pn =1;
        String pageNo = request.getParameter("pageNo");
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        System.out.println("pageSize = " + pageSize);
        if(pageNo==null){
            pn =1;
        }else{
            pn=Integer.parseInt(pageNo);
        }
        String areaName = request.getParameter("areaName");
        System.out.println("areaName = " + areaName);
        PageUtil<TArea> areaList = as.ListByPage(pn,pageSize,areaName);
        Gson g = new Gson();
        String json =g.toJson(areaList);
        System.out.println(json);
        pw.write(json);
    }
}
